package com.example.wenhua.controller;

import com.example.wenhua.common.Result;
import com.example.wenhua.entity.Sc;
import com.example.wenhua.service.ScService;
import com.example.wenhua.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 选课管理控制器
 */
@RestController
@RequestMapping("/api/sc")
@CrossOrigin(origins = "*")
public class ScController {
    
    @Autowired
    private ScService scService;
    
    /**
     * 查询所有选课记录（包含学生和课程详细信息，支持筛选）
     */
    @GetMapping
    public Result<List<Map<String, Object>>> getAllScRecords(
            @RequestParam(required = false) String sno,
            @RequestParam(required = false) String cno,
            @RequestParam(required = false) String gradeStatus) {
        try {
            LogUtil.info("开始查询选课记录，筛选条件: sno={}, cno={}, gradeStatus={}", sno, cno, gradeStatus);
            List<Map<String, Object>> records = scService.getScRecordsWithFilter(sno, cno, gradeStatus);
            LogUtil.info("查询到选课记录数量: {}", records.size());
            LogUtil.printJson("选课记录详细数据", records);
            
            Result<List<Map<String, Object>>> result = Result.success(records);
            LogUtil.printJson("返回给前端的完整响应", result);
            return result;
        } catch (Exception e) {
            LogUtil.error("查询选课记录失败: {}", e.getMessage(), e);
            return Result.error("查询选课记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据学号查询选课记录
     */
    @GetMapping("/student/{sno}")
    public Result<List<Sc>> getScRecordsBySno(@PathVariable String sno) {
        try {
            List<Sc> records = scService.getScRecordsBySno(sno);
            return Result.success(records);
        } catch (Exception e) {
            return Result.error("查询学生选课记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据课程号查询选课记录
     */
    @GetMapping("/course/{cno}")
    public Result<List<Sc>> getScRecordsByCno(@PathVariable String cno) {
        try {
            List<Sc> records = scService.getScRecordsByCno(cno);
            return Result.success(records);
        } catch (Exception e) {
            return Result.error("查询课程选课记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 学生选课
     */
    @PostMapping("/enroll")
    public Result<Void> enrollCourse(@RequestBody Map<String, String> request) {
        try {
            String sno = request.get("sno");
            String cno = request.get("cno");
            boolean success = scService.selectCourse(sno, cno);
            if (success) {
                return Result.success("选课成功", null);
            } else {
                return Result.error("选课失败");
            }
        } catch (Exception e) {
            return Result.error("选课失败：" + e.getMessage());
        }
    }
    
    /**
     * 学生退课
     */
    @DeleteMapping("/drop/{sno}/{cno}")
    public Result<Void> dropCourse(@PathVariable String sno, @PathVariable String cno) {
        try {
            boolean success = scService.dropCourse(sno, cno);
            if (success) {
                return Result.success("退课成功", null);
            } else {
                return Result.error("退课失败");
            }
        } catch (Exception e) {
            return Result.error("退课失败：" + e.getMessage());
        }
    }
    
    /**
     * 录入/更新成绩
     */
    @PutMapping("/grade")
    public Result<Void> updateGrade(@RequestBody Map<String, Object> request) {
        try {
            String sno = (String) request.get("sno");
            String cno = (String) request.get("cno");
            BigDecimal grade = new BigDecimal(request.get("grade").toString());
            boolean success = scService.updateGrade(sno, cno, grade);
            if (success) {
                return Result.success("成绩录入成功", null);
            } else {
                return Result.error("成绩录入失败");
            }
        } catch (Exception e) {
            return Result.error("成绩录入失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询学生各科成绩（包含课程信息）
     */
    @GetMapping("/grades/{sno}")
    public Result<List<Map<String, Object>>> getStudentGrades(@PathVariable String sno) {
        try {
            List<Map<String, Object>> grades = scService.getStudentGradesBySno(sno);
            return Result.success(grades);
        } catch (Exception e) {
            return Result.error("查询学生成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询课程不及格学生名单
     */
    @GetMapping("/fail/{cno}")
    public Result<List<Map<String, Object>>> getFailStudents(@PathVariable String cno) {
        try {
            List<Map<String, Object>> failStudents = scService.getFailStudentsByCno(cno);
            return Result.success(failStudents);
        } catch (Exception e) {
            return Result.error("查询不及格学生失败：" + e.getMessage());
        }
    }
    
    /**
     * 按班级统计不及格人数及比例
     */
    @GetMapping("/statistics/fail")
    public Result<List<Map<String, Object>>> getFailStatsByDept() {
        try {
            List<Map<String, Object>> stats = scService.getFailStatsByDept();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("查询不及格统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 按班级统计各分数段人数及比例
     */
    @GetMapping("/statistics/grade-range")
    public Result<List<Map<String, Object>>> getGradeRangeStats() {
        try {
            List<Map<String, Object>> stats = scService.getGradeRangeStatsByDept();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("查询分数段统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查学生是否已选某门课程
     */
    @GetMapping("/check")
    public Result<Boolean> checkEnrollment(@RequestParam String sno, @RequestParam String cno) {
        try {
            boolean enrolled = scService.isStudentEnrolled(sno, cno);
            return Result.success(enrolled);
        } catch (Exception e) {
            return Result.error("检查选课状态失败：" + e.getMessage());
        }
    }
}